package com.arpa.oms.controller;

import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.oms.domain.dto.OmsAllocationDTO;
import com.arpa.oms.domain.entity.OmsAllocation;
import com.arpa.oms.domain.vo.OmsAllocationVO;
import com.arpa.oms.domain.vo.OmsSaleReturnVO;
import com.arpa.oms.service.IOmsAllocationService;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.domain.consts.PropertyConst;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * OMS调拨单 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-11-17
 */
@Api(tags = "OMS调拨单")
//@RestController
@RequestMapping(value="/omsAllocation", produces = "application/json;charset=UTF-8")
@Log4j2(topic = "business")
public class OmsAllocationController {

   private final IOmsAllocationService  omsAllocationService;

    public OmsAllocationController(IOmsAllocationService omsAllocationService) {
        this.omsAllocationService = omsAllocationService;
    }

    /**
     * 获取 OMS调拨单 列表
     *
     * @param omsAllocationDTO
     * @return
     */
    @ApiOperation(value = "获取 OMS调拨单 列表", notes = "获取 OMS调拨单 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsAllocationVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(OmsAllocationDTO omsAllocationDTO) {
        try {
            omsAllocationDTO.setGroupCode(UserUtil.getBranchCode());
            omsAllocationDTO.setShipmentCode(UserUtil.getLoginWarehouseCodeOrShipmentCode());
            omsAllocationDTO.setWarehouseCodes(UserUtil.getShipmentAuthorizeWarehouseCodes());
            OmsAllocationVO omsAllocationVOSum = omsAllocationService.queryListSum(omsAllocationDTO);
            List<OmsAllocationVO> omsAllocationVOList = omsAllocationService.queryList(omsAllocationDTO);

            Page returnPage = new Page(omsAllocationDTO.getPageNum(),omsAllocationDTO.getPageSize());
            returnPage.setRecords(omsAllocationVOList);
            returnPage.setTotal(omsAllocationVOSum.getTotal());
            returnPage.setSumObject(omsAllocationVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 OMS调拨单
     *
     * @param entity OmsAllocation
     * @return
     */
    @ApiOperation(value = "添加 OMS调拨单 ", notes = "添加 OMS调拨单 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@RequestBody @Validated(OmsAllocation.Save.class) OmsAllocation entity) {
        try {
            omsAllocationService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取OMS调拨单详情
    *
    * @param code
    * @return
    */
    @ApiOperation(value = "获取OMS调拨单详情", notes = "获取OMS调拨单详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "OMS调拨单code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsAllocation.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result omsAllocation(@PathVariable String code) {
        try {
            OmsAllocationVO omsAllocationVO = omsAllocationService.getOneByCode(code);
            return Result.ok().data(omsAllocationVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改OMS调拨单
     *
     * @param entity OMS调拨单
     * @return
     */
    @ApiOperation(value = "修改OMS调拨单", notes = "修改OMS调拨单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Validated(OmsAllocation.Update.class) OmsAllocation entity) {
        int updateNum = omsAllocationService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 删除 OMS调拨单
     *
     * @param codes
     * @return
     */
    @ApiOperation(value = "删除 OMS调拨单 ", notes = "删除 OMS调拨单 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "codes", value = "调拨单标识", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes) {
        try {
            omsAllocationService.remove(new QueryWrapper<OmsAllocation>().lambda().in(OmsAllocation::getCode,codes));
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 审核 调拨单
     * @param entity
     * @return
     */
    @ApiOperation(value = "审核 OMS调拨单", notes = "审核 OMS调拨单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping(value = "/audit")
    public Result audit(@RequestBody OmsAllocation entity) {
        int updateNum = omsAllocationService.audit(entity);
        if(updateNum == 0){
            return Result.error(entity.getCode() + "审核失败!");
        }else{
            return Result.ok(entity.getCode() + "审核成功!");
        }
    }

    /**
     * 作废 调拨单
     * @param code
     * @return
     */
    @ApiOperation(value = "作废 调拨单", notes = "作废 调拨单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping(value = "/invalid/{code}")
    public Result invalid(@PathVariable("code") @NotEmpty(message = "调拨单号不能为空") String code) {
        int updateNum = omsAllocationService.invalid(code);
        if(updateNum == 0){
            return Result.error("调拨单号:" + code + "作废失败!");
        }else{
            return Result.ok("调拨单号:" + code + "作废成功!");
        }
    }

    /**
     * 查询入驻商
     * @return Map<String,String>
     */
    @ApiOperation(value = "查询入驻商", notes = "查询入驻商")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @GetMapping(value = "/getShipment")
    public Result getShipment() {
        try {
            Map<String,String> map = new HashMap<>(NumConst.NUM_TWO);
            String shipmentCompantName = UserUtil.getShipmentCompanyName();
            String partyCode = UserUtil.getCode();
            map.put(PropertyConst.SHIPMENT_CODE,partyCode);
            map.put(PropertyConst.SHIPMENT_NAME,shipmentCompantName);
            return Result.ok().data(map);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取 OMS调拨单 审核列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "获取 OMS调拨单 审核列表", notes = "获取 OMS调拨单 审核列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsSaleReturnVO.class))
    @NeedLogin
    @GetMapping("/auditList")
    public Result auditList(OmsAllocationDTO dto) {
        try {
            dto.setShipmentCode(UserUtil.getShipmentCompanyCode());

            // 前端传的审核状态为空的话，则只查询“待审核”、“审核不通过”、“审核通过”的数据
            if (StrUtil.isBlank(dto.getAuditStatus())) {
                List<String> auditStatus = Arrays.asList(NumConst.NUM_ONE.toString(), NumConst.NUM_TWO.toString(), NumConst.NUM_THREE.toString());
                String auditStatusStr = auditStatus.stream().map(c -> StrUtil.wrap(c, "'")).collect(Collectors.joining(","));
                dto.setAuditStatus(auditStatusStr);
            }

            OmsAllocationVO allocationVO = omsAllocationService.queryListSum(dto);
            allocationVO.setGroupCode(UserUtil.getBranchCode());
            List<OmsAllocationVO> allocationVOS = omsAllocationService.queryList(dto);

            Page returnPage = new Page(dto.getPageNum(),dto.getPageSize());
            returnPage.setRecords(allocationVOS);
            returnPage.setTotal(allocationVO.getTotal());
            returnPage.setSumObject(allocationVO);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

 }
